struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    explicit ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution
{
public:
    ListNode* swapPairs(ListNode* head)
    {
        if(head == nullptr || head->next == nullptr)
            return head;
        ListNode* newhead = new ListNode(0);
        ListNode* prev = newhead;
        ListNode* cur = head;
        ListNode* next = cur->next;//cur指向head，如果传空的结点，访问空结点的next就出问题
        ListNode* nnext = next->next;//同理，next不能为空，也就是head—>next不能为空
        while(cur && next)
        {
            prev->next = next;
            next->next = cur;
            cur->next = nnext;

            prev = cur;
            cur = nnext;
            if(cur)     next = cur->next;//同理如果cur是空，访问会出错
            if(next)    nnext = next->next;
        }
        prev = newhead->next;
        delete newhead;
        return prev;
    }
};